import {ComponentFactoryResolver, ComponentRef, Directive, HostListener, Input, OnChanges, OnDestroy, SimpleChanges, Type, ViewContainerRef} from '@angular/core';
import {PopoversComponent} from '../components/popovers/popovers.component';
import {DynamicComponentOptions} from '../components/dynamic-component/dynamic-component.interface';

@Directive({
  selector: '[ngToolsPopover]'
})
export class PopoverDirective implements OnChanges, OnDestroy {
  private isChanged = false;
  private data: any;
  private instance;
  private componentRef: ComponentRef<PopoversComponent>;
  private title: any;
  private dynamicComponent: DynamicComponentOptions;

  constructor(private viewContainer: ViewContainerRef,
              private componentFactoryResolver: ComponentFactoryResolver) {
  }

  @Input() set ngToolsPopover(values: { title?: any, data: any, dynamicComponent?: DynamicComponentOptions }) {
    this.data = values.data;
    this.title = values.title;
    this.dynamicComponent = values.dynamicComponent;
    this.isChanged = true;
  }

  @HostListener('click', ['$event']) onClick(e) {
    this.instance.toggle();
  }

  applyChanges() {
    this.instance.title = this.title;
    this.instance.content = {data: this.data, dynamicComponent: this.dynamicComponent};
  }

  createComponent() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(PopoversComponent);
    this.componentRef = this.viewContainer.createComponent(componentFactory);
    this.instance = <PopoversComponent>this.componentRef.instance;
    this.instance.title = this.title;
    this.instance.content = {data: this.data, dynamicComponent: this.dynamicComponent};
  }

  ngOnChanges(changes: SimpleChanges): void {
    const ngToolsPopoverChanges = changes.ngToolsPopover;
    if (ngToolsPopoverChanges) {
      if (ngToolsPopoverChanges.firstChange) {
        this.createComponent();
      } else {
        this.applyChanges();
      }
    }
  }

  ngOnDestroy(): void {
    this.componentRef.destroy();
  }

}
